from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib.auth import login, authenticate

# Create your views here.
from django.urls import reverse


def login_view(request):
    if request.method == 'GET':
        return render(request, 'login/login.html')
    else:
        username = request.POST.get('username', '')
        pwd = request.POST.get('pwd', '')
        is_remember = request.POST.get('remember')
        response = redirect(reverse('app01:index'))
        tips = "账号或密码错误，请重新输入！"
        error_response = render(request, 'login/login.html', locals())
        if User.objects.filter(username=username):
            # 验证账号密码与模型User的账号密码一致
            user = authenticate(username=username, password=pwd)
            if user:
                login(request, user)
                if is_remember:
                    response.set_cookie('username', username)

                else:
                    response.delete_cookie('username')
                return response
            else:
                return error_response
        else:
            return error_response


def logout_view(request):
    response = redirect(reverse('login:login'))
    response.delete_cookie('username')
    response.delete_cookie('sessionid')
    return response


def jump_to_login(request):

    return redirect(reverse('login:login'))